package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.CsPlatformType;
import com.ruoyi.common.utils.SnowflakeIdGenerator;
import com.ruoyi.system.client.ServerChanIm;
import com.ruoyi.system.client.SteamDTApiClientService;
import com.ruoyi.system.client.impl.CsQaqApiClientServiceImpl;
import com.ruoyi.system.constant.MessageGenerator;
import com.ruoyi.system.domain.CsOrnamentName;
import com.ruoyi.system.domain.CsToken;
import com.ruoyi.system.domain.csqaq.Alteration;
import com.ruoyi.system.domain.csqaq.HomeDateResponse;
import com.ruoyi.system.domain.steamDt.BatchPlatformPriceVO;
import com.ruoyi.system.domain.steamDt.CsBaseInfoVO;
import com.ruoyi.system.domain.steamDt.PlatformBaseInfoVO;
import com.ruoyi.system.domain.steamDt.PlatformPriceVO;
import com.ruoyi.system.mapper.AlterationMapper;
import com.ruoyi.system.mapper.CsOrnamentNameMapper;
import com.ruoyi.system.service.ICsOrnamentNameService;
import com.ruoyi.system.service.ICsTokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 饰品名称Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-04
 */
@Service
@Slf4j
public class CsOrnamentNameServiceImpl extends ServiceImpl<CsOrnamentNameMapper, CsOrnamentName> implements ICsOrnamentNameService {
    @Autowired
    private CsOrnamentNameMapper csOrnamentNameMapper;

    @Autowired
    private SteamDTApiClientService steamDTApiClientService;

    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;

    @Autowired
    private CsQaqApiClientServiceImpl csQaqApiClientServiceImpl;

    @Autowired
    private ServerChanIm serverChanIm;

    @Autowired
    private AlterationMapper alterationMapper;

    @Autowired
    private ICsTokenService csTokenService;

    /**
     * 查询饰品名称
     *
     * @param id 饰品名称主键
     * @return 饰品名称
     */
    @Override
    public CsOrnamentName selectCsOrnamentNameById(String id) {
        return csOrnamentNameMapper.selectCsOrnamentNameById(id);
    }

    /**
     * 查询饰品名称列表
     *
     * @param csOrnamentName 饰品名称
     * @return 饰品名称
     */
    @Override
    public List<CsOrnamentName> selectCsOrnamentNameList(CsOrnamentName csOrnamentName) {
        return csOrnamentNameMapper.selectList(new LambdaQueryWrapper<CsOrnamentName>()
                .like(!ObjectUtils.isEmpty(csOrnamentName.getMarketHashName()), CsOrnamentName::getMarketHashName, csOrnamentName.getMarketHashName())
                .like(!ObjectUtils.isEmpty(csOrnamentName.getName()), CsOrnamentName::getName, csOrnamentName.getName())
                .orderByDesc(CsOrnamentName::getUpdateDate)
        );
    }

    @Override
    public List<CsOrnamentName> selectCsOrnamentNameList(List<String> marketHashNameList) {
        return csOrnamentNameMapper.selectList(new LambdaQueryWrapper<CsOrnamentName>()
                .in(CsOrnamentName::getMarketHashName, marketHashNameList));
    }

    /**
     * 新增饰品名称
     *
     * @param csOrnamentName 饰品名称
     * @return 结果
     */
    @Override
    public int insertCsOrnamentName(CsOrnamentName csOrnamentName) {
        return csOrnamentNameMapper.insertCsOrnamentName(csOrnamentName);
    }

    /**
     * 修改饰品名称
     *
     * @param csOrnamentName 饰品名称
     * @return 结果
     */
    @Override
    public int updateCsOrnamentNameStatusById(CsOrnamentName csOrnamentName) {
        return csOrnamentNameMapper.update(null, new LambdaUpdateWrapper<CsOrnamentName>()
                .eq(CsOrnamentName::getId, csOrnamentName.getId())
                .set(CsOrnamentName::getStatus, csOrnamentName.getStatus()));
    }

    @Override
    public int updateCsOrnamentNameStatusByMarketHashName(String marketHashName, Long status) {
        return csOrnamentNameMapper.update(null, new LambdaUpdateWrapper<CsOrnamentName>()
                .eq(CsOrnamentName::getMarketHashName, marketHashName)
                .set(CsOrnamentName::getStatus, status));
    }

    /**
     * 批量删除饰品名称
     *
     * @param ids 需要删除的饰品名称主键
     * @return 结果
     */
    @Override
    public int deleteCsOrnamentNameByIds(String ids) {
        return csOrnamentNameMapper.deleteCsOrnamentNameByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除饰品名称信息
     *
     * @param id 饰品名称主键
     * @return 结果
     */
    @Override
    public int deleteCsOrnamentNameById(String id) {
        return csOrnamentNameMapper.deleteCsOrnamentNameById(id);
    }

    @Override
    public List<String> selectCsOrnamentNameList() {
        return csOrnamentNameMapper.selectCsOrnamentNameList(null).stream().map(CsOrnamentName::getName).collect(Collectors.toList());
    }


    @Override
    public void refreshCsBaseInfoBySteamDt() {
        // 刷新所有饰品的基础信息
        List<CsBaseInfoVO> allCsBaseInfoVO = steamDTApiClientService.getAllCsBaseInfoVO();
        List<CsOrnamentName> csOrnamentNames = csOrnamentNameMapper.selectList(null);
        Map<String, CsOrnamentName> ornamentNameMap = csOrnamentNames.stream().collect(Collectors.toMap(CsOrnamentName::getMarketHashName, Function.identity()));
        int start = 0;
        int end = 1000;
        do {
            List<CsOrnamentName> list = new ArrayList<>();
            end = Math.min(end, allCsBaseInfoVO.size());
            List<CsBaseInfoVO> csBaseInfoVOS = allCsBaseInfoVO.subList(start, end);
            for (CsBaseInfoVO csBaseInfoVO : csBaseInfoVOS) {
                CsOrnamentName csOrnamentName = ornamentNameMap.get(csBaseInfoVO.getMarketHashName());
                if (csOrnamentName == null) {
                    csOrnamentName = new CsOrnamentName();
                    csOrnamentName.setId(snowflakeIdGenerator.nextId());
                    csOrnamentName.setName(csBaseInfoVO.getName());
                    csOrnamentName.setMarketHashName(csBaseInfoVO.getMarketHashName());
                    csOrnamentName.setPlatformList(JSONObject.toJSONString(csBaseInfoVO.getPlatformList()));
                } else {
                    csOrnamentName.setMarketHashName(csBaseInfoVO.getMarketHashName());
                    csOrnamentName.setPlatformList(JSONObject.toJSONString(csBaseInfoVO.getPlatformList()));
                }
                if (!ObjectUtils.isEmpty(csBaseInfoVO.getPlatformList())) {
                    for (PlatformBaseInfoVO platformBaseInfoVO : csBaseInfoVO.getPlatformList()) {
                        if (platformBaseInfoVO.getName().equals("C5")) {
                            csOrnamentName.setC5ItemId(Long.valueOf(platformBaseInfoVO.getItemId()));
                        } else if (platformBaseInfoVO.getName().equals("YOUPIN")) {
                            csOrnamentName.setYyypItemId(Long.valueOf(platformBaseInfoVO.getItemId()));
                        } else if (platformBaseInfoVO.getName().equals("BUFF")) {
                            csOrnamentName.setBuffItemId(Long.valueOf(platformBaseInfoVO.getItemId()));
                        } else {
                            continue;
                        }
                    }
                }
                list.add(csOrnamentName);
            }
            if (!list.isEmpty()) {
                csOrnamentNameMapper.batchUpset(list);
            }
            list.clear();
            start = end;
            end += 1000;
        } while (start < allCsBaseInfoVO.size());
    }

    @Override
    public CsOrnamentName selectCsOrnamentNameByMarketHashName(String marketHashName) {
        return csOrnamentNameMapper.selectOne(new QueryWrapper<CsOrnamentName>()
                .eq("market_hash_name", marketHashName));
    }

    @Override
    public void getAbnormalMovementByCsQaq() {
        // 只获取关注的饰品异动信息
        List<CsOrnamentName> csOrnamentNames = csOrnamentNameMapper.selectList(new LambdaQueryWrapper<CsOrnamentName>()
                .apply("status & 2 > 0"));
        Set<Long> focusedGoodIds = csOrnamentNames.stream()
                .map(CsOrnamentName::getCsQaqId)
                .collect(Collectors.toSet());
        HomeDateResponse csQaqCurrentData = csQaqApiClientServiceImpl.getCsQaqCurrentData();
        List<Alteration> alterations = csQaqCurrentData.getData().getAlteration().subList(0, 10);
        if (alterations.isEmpty()) {
            return;
        }
        // 查询这个集合的数据 在数据库中有没有
        List<String> createdAts = alterations.stream().map(Alteration::getCreatedAt).collect(Collectors.toList());
        List<Long> goodIds = alterations.stream()
                .map(Alteration::getGoodid)
                .collect(Collectors.toList());

        LambdaQueryWrapper<Alteration> existsQuery = new LambdaQueryWrapper<>();
        existsQuery.in(Alteration::getCreatedAt, createdAts)
                .in(Alteration::getGoodid, goodIds)
                .select(Alteration::getGoodid, Alteration::getCreatedAt);
        List<Alteration> existingAlterations = alterationMapper.selectList(existsQuery);
        List<Alteration> insetDate;
        if (!ObjectUtils.isEmpty(existingAlterations)) {
            // 构建已存在记录的键集合
            Set<String> existingKeys = existingAlterations.stream()
                    .map(a -> a.getGoodid() + "_" + a.getCreatedAt())
                    .collect(Collectors.toSet());
            // 过滤出不在数据库中的记录（新记录）
            insetDate = alterations.stream()
                    .filter(a -> !existingKeys.contains(a.getGoodid() + "_" + a.getCreatedAt()))
                    .collect(Collectors.toList());
            ;
        } else {
            insetDate = new ArrayList<>(alterations);
        }
        if (insetDate.isEmpty()) {
            return;
        }
        for (Alteration alteration : insetDate) {
            alteration.setId(snowflakeIdGenerator.nextId());
            alteration.setStatus(0);
            if (focusedGoodIds.contains(alteration.getGoodid())) {
                // 触发推送
                serverChanIm.scSend("饰品异动", MessageGenerator.generateMessage(alteration), "CS");
                alteration.setStatus(1);
            }
        }
        alterationMapper.batchInsert(insetDate);
    }

    @Override
    @Transactional
    public void refreshCsOrnamentNamePlatformPriceBySteamDT() {
        // 获取当前库存的数据
        List<CsOrnamentName> csOrnamentNames = csOrnamentNameMapper.selectList(new LambdaQueryWrapper<CsOrnamentName>()
                .ne(CsOrnamentName::getStatus, 0)
                .orderByAsc(CsOrnamentName::getUpdateDate)
                .last("limit 99"));
        if (ObjectUtils.isEmpty(csOrnamentNames)) {
            return;
        }
        List<String> marketHashNames = csOrnamentNames.stream().map(CsOrnamentName::getMarketHashName).collect(Collectors.toList());
        String steamDtBearerToken = csTokenService.selectSteamDtBearerTokenByTimestamp();
        if (ObjectUtils.isEmpty(steamDtBearerToken)) {
            log.error("steamDT获取BearerToken失败");
            return;
        }
        List<BatchPlatformPriceVO> batchPriceByMarketHashNames = steamDTApiClientService.getBatchPriceByMarketHashNames(marketHashNames, steamDtBearerToken);
        if (ObjectUtils.isEmpty(batchPriceByMarketHashNames)) {
            log.error("steamDT获取平台价格失败");
            return;
        }
        Map<String, List<BatchPlatformPriceVO>> marketHashNameMap = batchPriceByMarketHashNames.stream().collect(Collectors.groupingBy(BatchPlatformPriceVO::getMarketHashName));
        for (CsOrnamentName csOrnamentName : csOrnamentNames) {
            List<BatchPlatformPriceVO> batchPlatformPriceVOS = marketHashNameMap.get(csOrnamentName.getMarketHashName());
            if (!ObjectUtils.isEmpty(batchPlatformPriceVOS)) {
                csOrnamentName.setUpdateDate(new Date());
                for (BatchPlatformPriceVO batchPlatformPriceVO : batchPlatformPriceVOS) {
                    for (PlatformPriceVO platformPriceVO : batchPlatformPriceVO.getDataList()) {
                        long sellPrice = (long) (platformPriceVO.getSellPrice() * 100);
                        if (platformPriceVO.getPlatform().equals(CsPlatformType.STEAM.desc())) {
                            csOrnamentName.setSteamPrice(sellPrice);
                            csOrnamentName.setSteamBalancePrice((long) (sellPrice * 0.8));
                        } else if (platformPriceVO.getPlatform().equals(CsPlatformType.UU.desc())) {
                            csOrnamentName.setYyypPrice(sellPrice);
                        } else if (platformPriceVO.getPlatform().equals(CsPlatformType.C5.desc())) {
                            csOrnamentName.setC5Price(sellPrice);
                        } else if (platformPriceVO.getPlatform().equals(CsPlatformType.BUFF.desc())) {
                            csOrnamentName.setBuffPrice(sellPrice);
                        }
                    }
                    if (csOrnamentName.getSteamPrice() != null) {
                        if (csOrnamentName.getYyypPrice() != null) {
                            csOrnamentName.setSteamBalanceDiscountByYyyp((long) (csOrnamentName.getYyypPrice() / (csOrnamentName.getSteamPrice() * 0.87) * 10000));
                        }
                        if (csOrnamentName.getC5Price() != null) {
                            csOrnamentName.setSteamBalanceDiscountByC5((long) (csOrnamentName.getC5Price() / (csOrnamentName.getSteamPrice() * 0.87) * 10000));
                        }
                        if (csOrnamentName.getBuffPrice() != null) {
                            csOrnamentName.setSteamBalanceDiscountByBuff((long) (csOrnamentName.getBuffPrice() / (csOrnamentName.getSteamPrice() * 0.87) * 10000));
                        }
                    }
                }
            }
        }
        csOrnamentNameMapper.batchUpdatePlatformPrice(csOrnamentNames);
    }

}
